package net.ming616.nlp.ictclas.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import net.ming616.nlp.common.model.NLPWord;
import net.ming616.nlp.ictclas.service.ICTCLASManager;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import ICTCLAS.kevin.zhang.ICTCLAS2011;

@Service("ictclasManager")
public class ICTCLASManagerImpl implements ICTCLASManager {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(ICTCLASManagerImpl.class);

	ICTCLAS2011 ictclas = new ICTCLAS2011();

	String encoding = "UTF-8";

	@SuppressWarnings("static-access")
	@PostConstruct
	void init() {
		try {
			String argu = ".";
			if (this.ictclas.ICTCLAS_Init(argu.getBytes(this.encoding), 1) == false) {
				logger.error("ICACLAS JIN init failed!");
				// System.exit(-1);
				return;
			} else {
				logger.info("ICACLAS JIN init successfully");
			}
			/*
			 * 设置词性标注集 ID 代表词性集 1 计算所一级标注集 0 计算所二级标注集 2 北大二级标注集 3 北大一级标注集
			 */
			this.ictclas.ICTCLAS_SetPOSmap(0);
			// import user dict
			int nCount = ictclas.ICTCLAS_ImportUserDict("userdict.txt"
					.getBytes());
			logger.info("import user words " + nCount);
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}

	}

	public String segment(String sentence) {
		String nativeStr = null;
		try {
			byte nativeBytes[] = ictclas.ICTCLAS_ParagraphProcess(
					sentence.getBytes(this.encoding), 1);
			nativeStr = new String(nativeBytes, 0, nativeBytes.length - 1,
					this.encoding);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return nativeStr;
	}

	public List<NLPWord> segmentToNLPWord(String sentence) {
		String result = this.segment(sentence);
		List<NLPWord> words = new ArrayList<NLPWord>();
		String[] results = StringUtils.split(result, " ");
		for (int i = 0; i < results.length; i++) {
			NLPWord nlpWord = new NLPWord();
			nlpWord.setId(i);
			nlpWord.setText(StringUtils.substringBeforeLast(results[i], "/"));
			nlpWord.setPos(StringUtils.substringAfterLast(results[i], "/"));
			words.add(nlpWord);
		}
		return words;
	}

}
